﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Windows.Media;
using System.Windows.Data;
using System.Data.OracleClient;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using DSTWBPACK;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Database;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.FTPClient;
using ReflectionStudio.Core.Helpers;
using System.Speech;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for DSTWBPACK.xaml
    /// </summary>
    public partial class DSTWBPACK : DocumentBase
    {
        #region-------------Properties-----------------------
        public OracleConnection OracleDB;
        public OracleCommand orlReadCommand = new OracleCommand();
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        public DataSet dsResult;
        DSTWBPACKData m_Data, m_DataX;
        string KRS = "", LFD = "", POS = "";
        string LastWBBSTKNR = "";
        string word2speak;

        public CollectionViewSource vwTXTKON
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwTXTKON");
            }
        }
        public DataRow dwTXTKON
        {
            get
            {
                if (vwTXTKON.View != null)
                {
                    return ((DataRowView)vwTXTKON.View.CurrentItem).Row;
                }
                return null;
            }
        }
        public CollectionViewSource vwTBPACK
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwTBPACK");
            }
        }
        public CollectionViewSource vwVKPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwVKPOS");
            }
        }
        public DataRow dwVKPOS
        {
            get
            {
                if (vwVKPOS.View != null)
                {
                    if (vwVKPOS.View.CurrentItem != null)
                    {
                        return ((DataRowView)vwVKPOS.View.CurrentItem).Row;
                    }
                }
                return null;
            }
        }
        public SETDSTWBPACK setUI
        {
            get
            {
                return (SETDSTWBPACK)this.TryFindResource("SETUI");
            }
        }
        string WBBSTKNR
        {
            get
            {
                return m_Data.Left(txtWBBSTKNR.Text.ToString().Trim() + "                                ", 12);
            }
        }
        DataTable tbWBBST
        {
            get
            {
                return setUI.WBBST;
            }
        }
        DataTable TBPack
        {
            get
            {
                return setUI.TBPACK;
            }
        }
        public DataRow dwVVLIEFSCH;
        public DataRow dwCOLOR;
        public DataRow dwWBBST;
        public DataSet dsParamaters;
        DSTWBPACKReport m_rpt;
        ArrayList listVV06, ListColor, listBatchNo;
        DataTable TBPacked;
        bool IsPrinted = false;
        #endregion
        public DSTWBPACK()
        {
            InitializeComponent();
            this.Name = "包装成件";
        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            base.SetUp(dicParamater);
            this.dicParamater = dicParamater;
            OracleDB = (OracleConnection)dicParamater["OracleDB"];
            proxy = (IntexReptServBLClient)dicParamater["proxy"];
            m_Data = new DSTWBPACKData(dicParamater);
            m_Data.OracleDB = OracleDB;
            m_Data.proxy = proxy;
            SetUpFtp();
            btnLogFTP_Click(null, null);
            txtWBBSTKNR.Focus();
            //txtWBBSTKNR.Text = "005331-01";
        }
        public void btnLogFTP_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string ftpsite = txtFTPSite.Text.Trim();
                string ftpport = txtFTPPort.Text.Trim();
                string ftpuser = txtFTPUser.Text.Trim();
                CheckFtp(ftpsite, ftpport, ftpuser, txtFTPPwd, IsBelongs2Admin.IsChecked == true);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
                //MessageBox.Show("FTP登录信息有误。请联系你们的破管理员。");
            }
            finally
            {
                ftpClient.Close();
            }
        }

        private void GenerateReport(string PrintType)
        {
            try
            {
                m_rpt = new DSTWBPACKReport(dicParamater);
                m_rpt.dsSource = setUI.Copy();
                m_rpt.PrintType = PrintType;
                m_rpt.ftpClient = ftpClient;
                if (m_Data.exAgent._app == null)
                {
                    m_Data.exAgent = new ExcelX.ExcelLib.ExcelAgent(dicParamater);
                }
                m_rpt.proxy = this.proxy;
                m_rpt.OracleDB = this.OracleDB;
                m_rpt.exAgent = m_Data.exAgent;
                bool allpcs = false;
                if (IsAllPcs.IsChecked == true)
                {
                    allpcs = true;
                }
                if (!allpcs)
                {
                    m_rpt.dsSource.Tables["WBBST"].Clear();
                    m_rpt.dsSource.Tables["WBBST"].Merge(TBPacked);
                }
                m_rpt.WriteExcelReport("EXCEL");
                IsPrinted = true;
                TBPacked.Clear();
                TBPacked.AcceptChanges();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnFinishPack_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SavePack();
                txtWBBSTKNR.Text = "";
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void SavePack()
        {
            if (TBPack.Rows.Count == 0)
                return;
            m_Data.SavePack(TBPack);
            if (TBPacked == null)
                TBPacked = TBPack.Clone();
            TBPacked.Merge(TBPack);
            TBPack.Clear();
            SetPackID();
            txtWBBSTKNR.Text = "";
            UpdateLength();
        }
        private void btnPrintPackLabel_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string PrintType = "OpenExcel";
                GenerateReport(PrintType);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void Reset()
        {
            try
            {
                if (!IsPrinted)
                {
                    if (dwVKPOS != null)
                    {
                        string PrintType = "OpenExcel";
                        //GenerateReport(PrintType);
                        //Tracer.Error("DSTWBPACK", "下次注意保存打印");
                        //MessageBox.Show("下次注意保存打印!");
                    }
                }
                IsPrinted = false;
                txtHistoryShade.Text = "";
                DataSet setResult = m_Data.GetWBBST(LastWBBSTKNR);
                setUI.Clear();
                setUI.Merge(setResult);
                setUI.AcceptChanges();
                if (vwVKPOS.View != null)
                {
                    vwVKPOS.View.MoveCurrentToFirst();
                    if (dwVKPOS != null)
                    {
                        if (POS != "XXX")
                        {
                            txtOrderQty.Text = (System.Convert.ToDouble(dwVKPOS["VKPMENGE1"].ToString()) * 0.01).ToString();
                            txtUM.Text = dwVKPOS["VKPMEEH"].ToString();
                        }
                    }
                }
                if (vwTXTKON.View != null)
                {
                    vwTXTKON.View.MoveCurrentToFirst();
                    txt010.Text = m_Data.Convert8859P1ToGB2312(dwTXTKON["TXT010"].ToString());
                    txt020.Text = m_Data.Convert8859P1ToGB2312(dwTXTKON["TXT020"].ToString());
                    txt030.Text = m_Data.Convert8859P1ToGB2312(dwTXTKON["TXT030"].ToString());
                }
                SetPackID();
                UpdateLength();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void SetPackID()
        {
            string packid = "1";
            var query = (from dwTemp in tbWBBST.AsEnumerable()
                         select System.Convert.ToInt16("0"+dwTemp["WBBBEM"].ToString())).Max();
            packid = query.ToString().Trim();
            if (packid == "")
                packid = "1";
            else
            {
                packid = m_Data.Right("000" + (1 + System.Convert.ToInt64(packid)), 3);
            }
            txtWBPACKNR.Text = packid;
            txtHistoryShade.Text = "";
            txtPackLength.Text = "0";
        }
        private void UpdateLength()
        {
            try
            {
                var query = (from dwTemp in tbWBBST.AsEnumerable()
                             select System.Convert.ToDouble(dwTemp["WBBISTKLG"].ToString()) * 0.001).Sum();
                double ttlWBLength = query;
                txtTTLWBLength.Text = ttlWBLength.ToString();
                query = (from dwTemp in tbWBBST.AsEnumerable()
                         where dwTemp["WBBBEM"].ToString().Substring(0, 4).Trim() == ""
                         select System.Convert.ToDouble(dwTemp["WBBISTKLG"].ToString()) * 0.001).Sum();
                double restWBLength = query;
                txtRestWBLength.Text = restWBLength.ToString();
                txtPackedWBLength.Text = (ttlWBLength - restWBLength).ToString();
                txtPackPcs.Text = "(" + TBPack.Rows.Count.ToString() + ")卷";
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void ColorBackGround()
        {
            try
            {
                var row = dlgWBBST.ItemContainerGenerator.ContainerFromItem(dlgWBBST.Items[0]) as DataGridRow;
                row.Background = new SolidColorBrush(Colors.Red);

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void TextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            try
            {
                if (e.Key != System.Windows.Input.Key.Enter) return;
                if (WBBSTKNR == "")
                    return;
                if (WBBSTKNR.Trim() == "0"
                    || WBBSTKNR.Trim() == "完成此件"
                    || WBBSTKNR.Trim() == "WFPACKBOX")
                {
                    btnFinishPack_Click(null, null);
                    return;
                }

                LastWBBSTKNR = WBBSTKNR;
                string expression = "WBBSTKNR='" + WBBSTKNR + "'";
                DataRow[] rows = setUI.Tables["WBBST"].Select(expression);
                if (rows.Length == 0)
                {
                    Reset();

                }
                rows = setUI.Tables["WBBST"].Select(expression);
                if (rows.Length == 0)
                {
                    System.Media.SystemSounds.Question.Play();
                    Tracer.Error("DSTWBPACK", "找不到布卷数据，请核对一下卷号");
                    //MessageBox.Show("找不到布卷数据，请核对一下卷号!");
                }

                DataRow dwWBBST = rows[0];
                string wbbem = dwWBBST["WBBBEM"].ToString();
                wbbem = m_Data.Right(wbbem + "                                             ", 15);
                dwWBBST["WBBBEM"] = m_Data.Right("0000" + txtWBPACKNR.Text.ToString(), 3) + m_Data.Right(wbbem, 12);
                if (TBPack.Rows.Count == 0)
                {
                    txtHistoryShade.Text = dwWBBST["WBBTAX"].ToString();
                }
                if (TBPack.Rows.Count > 0)
                {
                    if (txtHistoryShade.Text.ToString().Trim() != dwWBBST["WBBTAX"].ToString().Trim())
                    {
                        System.Media.SystemSounds.Question.Play();
                        //MessageBox.Show("色光违背约束，请核对!");
                        Tracer.Error("DSTWBPACK", "色光违背约束，请核对");
                        //return;
                    }
                }

                TBPack.Merge(rows.CopyToDataTable());
                vwTBPACK.View.MoveCurrentToFirst();
                DataRowView dwPack;
                while (true)
                {
                    dwPack = (DataRowView)vwTBPACK.View.CurrentItem;
                    if (dwPack == null)
                        break;
                    if (dwPack.Row["WBBSTKNR"].ToString() == WBBSTKNR)
                        break;
                    else
                    {
                        vwTBPACK.View.MoveCurrentToNext();
                    }
                }
                var query = (from dwTemp in TBPack.AsEnumerable()
                             select System.Convert.ToDouble(dwTemp["WBBISTKLG"].ToString()) * 0.001).Sum();
                double packleng = query;
                txtPackLength.Text = packleng.ToString();
                System.Media.SystemSounds.Beep.Play();
                word2speak = "";
                txtWBBSTKNR.Text = "";
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            //EventDispatcher.Instance.voice.Speak(word2speak, SpeechVoiceSpeakFlags.SVSFlagsAsync);
        }
        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Reset();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }

        private void txtWBPACKNR_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                SavePack();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }
    }
}
